from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializer import *
from django.core.paginator import Paginator

class CateView(APIView):
    def post(self,request):
        name=request.POST.get("name")
        obj=models.Cate.objects.filter(name=name).first()
        if obj:
            return Response({"code":1003,"msg":"分类存在"})
        data={
            'name':name,
        }
        obj=Cateserializers(data=data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({"code":1000,"msg":"添加成功"})
            return Response({"code":1001,"msg":"添加失败"})
        print(obj.errors)
        return Response({"code":1002,"msg":"参数错误"})



class GoodsViews(APIView):
    #查询

    def get(self,request):
        p=request.GET.get("p",1)
        obj_all=models.Goods.objects.all()
        page_obj=Paginator(obj_all,per_page=3)
        page=[i for i in page_obj.page_range]
        page_data=page_obj.page(p)
        previous=page_data.has_previous()
        next=page_data.has_next()
        obj=Goodserializers(page_data,many=True)
        data={
            "data":obj.data,
            "page":page,
            "previous":previous,
            'next':next
        }
        return Response({"code":1000,"data":data})
    #添加
    def post(self,request):
        name=request.POST.get("name")
        price=request.POST.get("price")
        img=request.FILES.get("img")
        obj=models.Goods.objects.filter(name=name).first()
        if obj:
            return Response({"code":1003,"msg":"商品存在"})
        data={
            'name':name,
            'price':price,
            'img':img
        }
        obj=Goodserializers(data=data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({"code":1000,"msg":"添加成功"})
            return Response({"code":1001,"msg":"添加失败"})
        print(obj.errors)
        return Response({"code":1002,"msg":"参数错误"})
class DetailView(APIView):
    def get(self,request):
        id=request.GET.get("id")
        objall=models.Goods.objects.filter(id=id).first()
        obj=Goodserializers(objall)
        return Response({"code":1000,"data":obj.data})